import React, {PureComponent} from 'react';
import { routerRedux } from 'dva/router';
import {connect } from 'dva';
import {
    Row,
    Col,
    Card,
    Form,
    Input,
    Select,
    Button,
    Modal,
    message,
    AutoComplete
} from 'antd';
import moment from 'moment';
import PageHeaderLayout from '../../../layouts/PageHeaderLayout';
import styles from './goodsManage.less';
import GoodsManageTable from '../../../components/goods/goodsManage';
import GoodsEdit from '../../../components/goods/goodsManage/GoodsEdit';
import RecObjectAdd from '../../../components/Operation/RecObject/RecObjectAdd'
import {powerControl} from '../../../utils/powerControl';
import data from "../../../common/nav";
const AuthButton = powerControl(Button);
const FormItem = Form.Item;
const {Option} = Select;
const getValue = obj => Object.keys(obj).map(key => obj[key]).join(',');
@connect((state)=>({
    goodsManage:state.goodsManage,
}))
@Form.create()
export default class GoodsManage extends PureComponent{
    state={
        modalVisible: false,
        formValues:{},
        editType: 'add',
        record: {},
        recObjectVisible:false,
        returnPath:{},
        dataSourceList:[],
        dataSource: [],
        data:{},
    };
        componentDidMount(){
        this.props.dispatch({
            type:'goodsManage/fetch',
            callback: (response) => {
                if (response.resultData.goodsManage !== null){
                    if (response.resultData.goodsManage.list.length > 0){
                        this.setState({
                            data: response.resultData.goodsManage,
                        });
                    }else {
                        message.success('没有数据！');
                    }
                }
            }
        });
        const userObj=JSON.parse(localStorage.getItem("userInfoState"));
        this.props.dispatch({
            type:'goodsManage/queryShopList',
            payload: {
              user_id: userObj.userInfo.user_id,
            },
            callback: (response) => {
                if (response.resultData.shopList !== null && response.resultData.shopList.length > 0){
                    this.setState({
                        dataSourceList: response.resultData.shopList,
                    });
                }
            }
        });
    }
    handleFormReset = () => {
        const {form, dispatch} = this.props;
        form.resetFields();
    };
    handleSearch = (e) => {
        e.preventDefault();
        const {dispatch, form} = this.props;
        form.validateFields((err, fieldsValue) => {
            if (err) return;
            this.setState({
                formValues: fieldsValue,
            });
            dispatch({
                type: 'goodsManage/fetch',
                payload: fieldsValue,
                callback: (response) => {
                    if (response.resultData.goodsManage !== null){
                        if (response.resultData.goodsManage.list.length > 0){
                            this.setState({
                                data: response.resultData.goodsManage,
                            });
                        }else {
                            message.success('没有数据！');
                        }
                    }
                }
            });
        });
    };
    renderForm() {
        return this.renderSimpleForm();
    };

    handleAddGood = () => {
        const {dispatch} = this.props;
        // this.handleModalVisible(true);
        dispatch({
            type: 'goodsManage/keepData',
            payload: {
                editType: 'add',
                returnPath:'/goods/GoodsManage'
            },
        });
        dispatch(routerRedux.push('/goods/addGoods'));
    };
    handleModalVisible = (flag) => {
        this.setState({
            modalVisible: !!flag,
        });
    };

    autoCHandleSearch = (value) =>{
        const {dataSourceList} = this.state;
        let data = [];
        if(!value){
            data = [];
        }else {
            dataSourceList.map((item) =>{
                if (item.shop_name !== null){
                    if(item.shop_name.indexOf(value)!==-1){
                        data.push(item);
                    }
                }
            });
        }
        this.setState({
            dataSource:data,
        });
    };

    /**
     * 推荐按钮事件
     * @param record
     * @param pagination
     */
    handleRecommendRow = (record, pagination) => {
        this.handlerecObjectVisible(true);
        this.setState({
            editType: 'add',
            record: record
        });
    }
    /**
     * 修改商品状态
     * @param goodsId
     * @param state
     * @param pagination
     */
    handleChangeOnsale = (goodsId,state, pagination) => {
        const {dispatch} = this.props;
        let me = this;
        dispatch({
            type: 'goodsManage/changeOnsale',
            payload: {goodsId: goodsId,isOnSale: state},
            callback: (response) => {
                if (response.result === 0) {
                    message.success('修改成功');
                    me.handleModalSuccess(pagination);
                } else {
                    message.success('修改失败');
                }
            }
        });
    }

    /**
     * 推荐对象模态框显示
     * @param flag
     */
    handlerecObjectVisible = (flag) => {
        this.setState({
            recObjectVisible: !!flag,
        })
    };

    /**
     * 推荐对象新增提交
     */
    handleRecObjectAdd = () => {
        this.props.dispatch({
            type: 'recObject/add',
            payload: {
                description: this.state.addInputValue,
            },
        });
        message.success('添加成功');
        this.setState({
            recObjectVisible: false,
        });
    }

    /**
     * 跳转到推荐对象页面
     * @constructor
     */
    returnRecObject = () => {
        const {dispatch} = this.props;
        dispatch(routerRedux.push('/operation/recObject'));
    };

    handleEditGoodRow = (record, pagination) => {
        const xiangou_date = [moment(record.xiangou_start_date, "YYYY-MM-DD HH:mm:ss"),moment(record.xiangou_end_date, "YYYY-MM-DD HH:mm:ss")];
        const promote_date = [moment(record.promote_start_date, "YYYY-MM-DD HH:mm:ss"),moment(record.promote_end_date, "YYYY-MM-DD HH:mm:ss")];
        const {dispatch} = this.props;
        dispatch({
            type: 'goodsManage/keepData',
            payload: {
                ...record,
                editType: 'mod',
                goods_id: record.goods_id,
                xiangou_date: xiangou_date,
                promote_date: promote_date,
                returnPath:'/goods/GoodsManage'
            },
        });
        dispatch(routerRedux.push('/goods/addGoods'));
        // this.handleModalVisible(true);
        // this.setState({
        //     editType: 'mod',
        //     record: record
        // });
    }
    handleDelGoodRow = (goods_id, pagination) => {
        const {dispatch} = this.props;
        dispatch({
            type: 'goodsManage/del',
            payload: {goods_id: goods_id},
            callback: (response) => {
                if (response.result === 0) {
                    message.success('删除成功');
                    this.handleModalSuccess(pagination);
                } else {
                    message.success('删除失败');
                }
            }
        });
    }
    handleModalSuccess = (pagination) => {
        const {dispatch} = this.props;
        const {formValues} = this.state;
        const params = {
            currentPage: pagination.current,
            pageSize: pagination.pageSize,
            ...formValues,
        };
        dispatch({
            type: 'goodsManage/fetch',
            payload: params,
            callback: (response) => {
                if (response.resultData.goodsManage !== null){
                    if (response.resultData.goodsManage.list.length > 0){
                        this.setState({
                            data: response.resultData.goodsManage,
                        });
                    }else {
                        message.success('没有数据！');
                    }
                }
            }
        });
    }
    handleGoodsListChange = (pagination, filtersArg, sorter) => {
        const {dispatch} = this.props;
        const {formValues} = this.state;

        const filters = Object.keys(filtersArg).reduce((obj, key) => {
            const newObj = {...obj};
            newObj[key] = getValue(filtersArg[key]);
            return newObj;
        }, {});

        const params = {
            currentPage: pagination.current,
            pageSize: pagination.pageSize,
            ...formValues,
            ...filters,
        };
        if (sorter.field) {
            params.sorter = `${sorter.field}_${sorter.order}`;
        }

        dispatch({
            type: 'goodsManage/fetch',
            payload: params,
            callback: (response) => {
                if (response.resultData.goodsManage !== null){
                    if (response.resultData.goodsManage.list.length > 0){
                        this.setState({
                            data: response.resultData.goodsManage,
                        });
                    }else {
                        message.success('没有数据！');
                    }
                }
            }
        });
    }
    renderSimpleForm() {
        const{form}=this.props;
        const {dataSource, dataSourceList}=this.state;
        const {getFieldDecorator} = form;
        const children = dataSource.map((item) => {
            return <Option value={String(item.id)}>{item.shop_name}</Option>;
        });
        return (
            <Form onSubmit={this.handleSearch} layout="inline">
                <Row gutter={{md: 8, lg: 24, xl: 48}}>
                    <Col md={6} sm={24}>
                        <FormItem label = "店铺名称">
                            {getFieldDecorator('sellerId')(
                                <AutoComplete
                                    placeholder="请输入"
                                    onSearch={this.autoCHandleSearch}
                                >
                                    {children}
                                </AutoComplete>
                            )}
                        </FormItem>
                    </Col>
                    <Col md={6} sm={24}>
                        <FormItem label="商品货号">
                            {getFieldDecorator('goods_sn')(
                                <Input placeholder="请输入"/>
                            )}
                        </FormItem>
                    </Col>
                    <Col md={6} sm={24}>
                        <FormItem label="商品名称">
                            {getFieldDecorator('goods_name')(
                                <Input placeholder="请输入"/>
                            )}
                        </FormItem>
                    </Col>
                    <Col md={6} sm={24}>
                        <span className={styles.sumbitButtons}>
                          <AuthButton auth="goodsManage.search" type="primary" htmlType="submit">查询</AuthButton>
                          <AuthButton auth="goodsManage.reset" style={{marginLeft: 8}} onClick={this.handleFormReset}>重置</AuthButton>
                        </span>
                    </Col>
                </Row>
            </Form>
        );
    };
    render(){
        const {recObjectVisible,editType,record, data} = this.state;
        const {goodsManage:{loading:ruleLoading}}=this.props;
        return (<PageHeaderLayout title="商品管理">
            <Card bordered={false}>
                <div className={styles.tableList}>
                    <div className={styles.tableListForm}>
                        {this.renderForm()}
                    </div>
                    <div className={styles.tableListOperator}>
                        <AuthButton auth="goodsManage.new" icon="plus" type="primary" onClick={() => this.handleAddGood()}>新建</AuthButton>
                    </div>
                    <GoodsManageTable
                    data={data}
                    loading={ruleLoading}
                    onEditRow={this.handleEditGoodRow}
                    onDelRow={this.handleDelGoodRow}
                    onChange={this.handleGoodsListChange}
                    onRecommendRow={this.handleRecommendRow}
                    handleChangeOnsale={this.handleChangeOnsale}/>
                </div>
            </Card>
            
            <Modal
                title="新增推荐对象"
                key={new Date()}
                width={700}
                visible={recObjectVisible}
                onOk={this.handleRecObjectAdd}
                onCancel={() => this.handlerecObjectVisible()}
                footer={null}
            >
                <RecObjectAdd  ref="recObjectAdd"
                               pagination={data.pagination}
                               editType={editType}
                               record={record}
                               type={1}
                               // categorySList={brandSList}
                               handlerecObjectVisible={this.handlerecObjectVisible}
                               returnRecObject={this.returnRecObject}
                />
            </Modal>
        </PageHeaderLayout>)
    }
}